import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:video_player_plus/LoadView.dart';

class FullScreen extends StatefulWidget {
  final VideoPlayerController controller;
  final bool play;

  const FullScreen({Key key, this.controller, this.play}) : super(key: key);

  @override
  _FullScreenState createState() => _FullScreenState();
}

class _FullScreenState extends State<FullScreen> {
  VideoPlayerController _controller;
  bool play = false;
  Function _function;
  Timer timer;
  var initialize;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    _function = () {
      if (!mounted) {
        return;
      }
      var duration = _controller.value.duration;
      var position = _controller.value.position;
      if (position.inMilliseconds > 0 && duration.compareTo(position) == 0) {
        setState(() {
          play = false;
        });
      }
    };
    _controller.addListener(_function);
    if (_controller.value.size.width > _controller.value.size.height) {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    } else {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    }
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      try {
        if (play) {
          setState(() {});
        }
      } catch (e) {
        timer.cancel();
      }
    });
    if (widget.play == true) {
      play = true;
      _controller.play();
    }
    initialize = getInitialize();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.removeListener(_function);
    timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          backgroundColor: Colors.black,
          body: Stack(
            children: <Widget>[
              Center(
                  child: FutureBuilder(
                      future: initialize,
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        //请求完成
                        if (snapshot.connectionState == ConnectionState.done) {
                          //发生错误
                          if (snapshot.hasError) {
                            debugPrint(snapshot.error.toString());
                            return Center(
                                child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                IconButton(
                                    icon: Icon(
                                      Icons.error_outline,
                                      color: Colors.white,
                                    ),
                                    onPressed: () {
                                      setState(() {
                                        initialize = getInitialize();
                                      });
                                    }),
                                Text(
                                  "视频加载失败",
                                  style: TextStyle(color: Colors.white),
                                )
                              ],
                            ));
                          }
                          return Stack(
                            children: <Widget>[
                              Center(
                                child: GestureDetector(
                                  child: Container(
                                    width: geWidth(_controller.value),
                                    height: getHeight(_controller.value),
                                    child: VideoPlayer(_controller),
                                  ),
                                  onTap: () {
                                    setState(() {
                                      play = false;
                                      _controller.pause();
                                    });
                                  },
                                ),
                              ),
                              Visibility(
                                child: Center(
                                  child: IconButton(
                                      icon: Icon(
                                        Icons.play_circle_outline,
                                        size: 40,
                                        color: Colors.white,
                                      ),
                                      onPressed: () {
                                        play = true;
                                        var duration =
                                            _controller.value.duration;
                                        var position =
                                            _controller.value.position;
                                        if (position.inMilliseconds > 0 &&
                                            duration.compareTo(position) == 0) {
                                          _controller.seekTo(Duration());
                                          setState(() {});
                                          return;
                                        }
                                        _controller.play();
                                        setState(() {});
                                      }),
                                ),
                                visible: !play,
                              ),
                              Positioned(
                                child: Visibility(
                                    child: Container(
                                  child: LinearProgressIndicator(
                                    backgroundColor: Colors.white10,
                                    value: getProgress(),
                                  ),
                                  height: 3,
                                  width: double.infinity,
                                )),
                                bottom: 0,
                                left: 0,
                                right: 0,
                              )
                            ],
                          );
                        }
                        return LoadView();
                      })),
              Positioned(
                child: AppBar(
                  backgroundColor: Colors.transparent,
                  elevation: 0,
                  leading: BackButton(
                    color: Colors.white,
                  ),
                ),
                top: 0,
                right: 0,
                left: 0,
              )
            ],
          ),
        ),
        onWillPop: () async {
          // 点击返回键的操作
          SystemChrome.setPreferredOrientations(
              [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
          return true;
        });
  }

  double geWidth(VideoPlayerValue value) {
    var aspectRatio = value.aspectRatio;
    double height = getHeight(value);
    double width = height * aspectRatio;
    double mWidth = MediaQuery.of(context).size.width;
    if (width > mWidth) {
      width = mWidth;
    }
    return width;
  }

  double getHeight(VideoPlayerValue value) {
    double height = MediaQuery.of(context).size.height;
    if (value.size.height < height) {
      height = value.size.height;
    }
    return height;
  }

  getProgress() {
    var duration = _controller.value.duration;
    var position = _controller.value.position;
    return position.inSeconds / duration.inSeconds;
  }

  getInitialize() {
    var initialized = _controller.value.initialized;
    return initialized
        ? Future(() {
            return null;
          })
        : _controller.initialize();
  }
}
